﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BudgetManager.Data;
using BudgetManager.Entities;
using BudgetManager.Resources;
using System.IO.IsolatedStorage;
using BudgetManager.Utils;

namespace BudgetManager
{
    public partial class AddExpense : PhoneApplicationPage
    {
        public bool isEdit = false;
        public AddExpense()
        {
            InitializeComponent();
            BuildLocalizedApplicationBar();
            LoadCategories();
        }

        #region EVENT_HANDLERS
        /// <summary>
        /// Save event for expense details
        /// </summary>
        private void saveBtnClicked(object sender, EventArgs e)
        {
            Expense expense = new Expense();
            expense.Category = lstCategory.SelectedItem.ToString();
            expense.Comments = string.IsNullOrEmpty(txtdescription.Text) ? "" : txtdescription.Text;
            expense.ExpenseDate = (DateTime)date.Value;
            expense.ExpenseAmount = string.IsNullOrEmpty(txtAmount.Text) ? 0 : float.Parse(txtAmount.Text);
            expense.IsActive = true;
            if (isEdit)
            {
                expense.ExpenseId = (IsolatedStorageSettings.ApplicationSettings["EditElement"] as ExpenseReport).ExpenseId;
                AppSettingsHelper.removeAppSettings("EditElement");
                new BudgetMgrDAL().UpdateExpense(expense);
            }
            else
            {
                new BudgetMgrDAL().AddExpense(expense);
            }
            MessageBox.Show(AppResources.ExpenseSaveSuccessfulMessage, AppResources.AlertBoxTitle, MessageBoxButton.OK);
            NavigationService.Navigate(new Uri(String.Format("/AddExpense.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
        }

        /// <summary>
        /// Data changed event foe enabling appbarbutton. Amount is mandatory to save expense
        /// </summary>
        private void onDataChanged(object sender, TextChangedEventArgs e)
        {
            if ((sender as TextBox).Text != "")
            {
                (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = true;
            }
            else
            {
                (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
            }
        }
        #endregion

        #region HELPER_METHODS
        /// <summary>
        /// Loads the categories dropdown
        /// </summary>
        private void LoadCategories()
        {
            lstCategory.ItemsSource = new BudgetMgrDAL().LoadCategories().Select(cat => cat.Name);
        }

        private void BuildLocalizedApplicationBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBarIconButton save = new ApplicationBarIconButton(new Uri("/Toolkit.Content/ApplicationBar.Check.png", UriKind.RelativeOrAbsolute));
            save.Text = AppResources.SaveBtnText;
            save.Click += saveBtnClicked;
            ApplicationBar.Buttons.Add(save);
        }
        #endregion
        
        #region OVERRIDED_METHODS
        /// <summary>
        /// OnNavigated event
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string id = string.Empty;
            ExpenseReport expense = new ExpenseReport();
            if (NavigationContext.QueryString.TryGetValue("id", out id))
            {
                if (NavigationService.CanGoBack)
                    NavigationService.RemoveBackEntry();
            }
            else if (NavigationContext.QueryString.Contains(new KeyValuePair<string, string>("expDetail","1")))
            {
                expense = IsolatedStorageSettings.ApplicationSettings["EditElement"] as ExpenseReport;
                lstCategory.SelectedItem = expense.Category;
                txtAmount.Text = expense.ExpenseAmount.ToString();
                txtdescription.Text = expense.Comments;
                date.Value = new DateTime(expense.Year, 2, expense.Date);
            }
        }
        #endregion
        

        
    }
}